#!/bin/bash

set -eu

# Only execute in the few pipelines that need it
# if this needs to be extended to other pipelines/steps, let the build team know to take their input on it
[[ "$BUILDKITE_PIPELINE_NAME" =~ (verify|validate/(release|adhoc|canary)|docker-build)$ ]] || exit 0

docker ps || true

# Get chef foundation version from the json file
CHEF_FOUNDATION_VERSION=$(cat .buildkite-platform.json | jq -r '.chef_foundation')
export CHEF_FOUNDATION_VERSION
echo "Chef Foundation Version: $CHEF_FOUNDATION_VERSION"

OMNIBUS_TOOLCHAIN_VERSION=$(cat .buildkite-platform.json | jq -r '.omnibus_toolchain')
export OMNIBUS_TOOLCHAIN_VERSION
echo "Omnibus Toolchain Version: $OMNIBUS_TOOLCHAIN_VERSION"

RUBY_VERSION=$(cat .buildkite-platform.json | jq -r '.ruby_version')
export RUBY_VERSION
echo "Proposed Ruby Version: $RUBY_VERSION"

if [[ "$BUILDKITE_STEP_KEY" =~ "build-windows" ]] && [[ "$BUILDKITE_ORGANIZATION_SLUG" =~ chef(-canary)?$ ]]
then
  TOKEN=$(curl -sX PUT "http://169.254.169.254/latest/api/token" -H "X-aws-ec2-metadata-token-ttl-seconds: 21600")
  ROLE=$(curl -sH "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/iam/security-credentials/)
  RESPONSE=$(curl -sH "X-aws-ec2-metadata-token: $TOKEN" -v http://169.254.169.254/latest/meta-data/iam/security-credentials/$ROLE)
  AWS_ACCESS_KEY_ID=$(echo $RESPONSE | jq -r '.AccessKeyId')
  export AWS_ACCESS_KEY_ID
  AWS_SECRET_ACCESS_KEY=$(echo $RESPONSE | jq -r '.SecretAccessKey')
  export AWS_SECRET_ACCESS_KEY
  AWS_SESSION_TOKEN=$(echo $RESPONSE | jq -r '.Token')
  export AWS_SESSION_TOKEN
fi

# We've now seen cases where origin/main on the build hosts can get
# out of date. This causes us to build components unnecessarily.
# Fetching it here hopefully will prevent this situation.
echo "Fetching origin/main"
git fetch origin main

# DEBUGGING FOR RELENG
# Fetch the git tags to see if that addresses the weird smart build behavior for Habitat
git fetch --tags --force

# Rebase onto current main to ensure this PR is closer to what happens when it's merged.
# Only do this if it's actually a branch (i.e. a PR or a manually created build), not a
# post-merge CI run of main.
if [[ "$BUILDKITE_BRANCH" != "main" ]]; then
  git config user.email "you@example.com" # these are needed for the rebase attempt
  git config user.name "Your Name"
  main=$(git show-ref -s --abbrev origin/main)
  pr_head=$(git show-ref -s --abbrev HEAD)
  github="https://github.com/chef/chef/commit/"
  if git rebase origin/main >/dev/null; then
    buildkite-agent annotate --style success --context "rebase-pr-branch-${main}" \
      "Rebased onto main ([${main}](${github}${main}))."
  else
    git rebase --abort
    buildkite-agent annotate --style warning --context "rebase-pr-branch-${main}" \
      "Couldn't rebase onto main ([${main}](${github}${main})), building PR HEAD ([${pr_head}](${github}${pr_head}))."
  fi
fi

if [[ $BUILDKITE_ORGANIZATION_SLUG = 'chef-canary' ]]; then
  export AWS_REGION='us-west-1'
elif [[ $BUILDKITE_ORGANIZATION_SLUG = 'chef' ]] || [[ $BUILDKITE_ORGANIZATION_SLUG = 'chef-oss' ]]; then
  export AWS_REGION='us-west-2'
fi

export HAB_AUTH_TOKEN=$(aws ssm get-parameter --name 'habitat-prod-auth-token' --with-decryption --query Parameter.Value --output text --region ${AWS_REGION})

if [[ ! "$BUILDKITE_STEP_KEY" =~ ^test.* ]] && [[ $BUILDKITE_ORGANIZATION_SLUG != "chef-oss" ]]; then
  if [[ ! $BUILDKITE_LABEL =~ macOS|mac_os_x ]]; then
    lita_password=$(aws ssm get-parameter --name "artifactory-lita-password" --with-decryption --query Parameter.Value --output text --region ${AWS_REGION})
    export ARTIFACTORY_API_KEY=$(echo -n "lita:${lita_password}" | base64)
  fi
  export ARTIFACTORY_PASSWORD=$(aws ssm get-parameter --name "buildkite-artifactory-docker-full-access-token" --query Parameter.Value --with-decryption --output text --region ${AWS_REGION})

  # Only if on RPM-based Linux distros
  if [[ "$BUILDKITE_LABEL" =~ rhel|rocky|sles|centos|amazon ]]; then
    export RPM_SIGNING_KEY=$(aws ssm get-parameter --name "packages-at-chef-io-signing-cert" --with-decryption --query Parameter.Value --output text --region ${AWS_REGION})
  fi
fi
